package com.mdc.mansion.common.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import com.mdc.mansion.common.exception.BusinessException;

public class MD5Utils {

    private static final String CHARSET = "UTF8";

    private static final String ALG = "MD5";
    
    /**
	 * 根据“密码字符串”、“时间对象”、“密钥字符串”生成MD5密文
	 * @param password
	 * @param time
	 * @param md5Key
	 * @return
	 */
	public static String generateMD5Password(String password, Date time,String md5Key) {
		return encryptWithKey(password + time.getTime(), md5Key);
	}

    public static String encrypt(String str) {
        byte[] digest = null;
        try {
            digest = DigestPass.digest(ALG, str.getBytes(CHARSET));
        } catch (NoSuchAlgorithmException e) {
            throw new BusinessException(e);
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(e);
        }
        return encode(digest);
    }

    public static String encryptWithKey(String str, String key) {
        byte[] digest = null;
        try {
            digest = DigestPass.digest(ALG, str.getBytes(CHARSET), key.getBytes(CHARSET));
        } catch (NoSuchAlgorithmException e) {
            throw new BusinessException(e);
        } catch (UnsupportedEncodingException e) {
            throw new BusinessException(e);
        }
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < digest.length; i++) {
            int val = ((int) digest[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return encode(digest);
    }

    public static String encode(byte[] plain) {
        return new String(Base64.encodeBase64(plain));
    }

    /***
     * MD5加码 生成32位md5码
     * 
     * @param inStr 被摘要字符串
     */
    public static String string2MD5(String inStr) {
        MessageDigest md5 = null;
        byte[] byteArray = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byteArray = inStr.getBytes("utf-8");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
    
    public static String string2MD5(String inStr,String charset) {
        MessageDigest md5 = null;
        byte[] byteArray = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byteArray = inStr.getBytes(charset);
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
    
    /***
     * MD5加码 生成16位md5码
     * 
     * @param inStr 被摘要字符串
     */
    public static String string2MD5L16(String inStr) {
        String string2md5 = string2MD5(inStr);
        if(StringUtils.isBlank(string2md5)){
            return string2md5;
        }
        return string2md5.toLowerCase().substring(8, 24);
    }
    
    // 对字符串进行MD5编码
    public static String string2MD5Big(String inStr) {
        MessageDigest md5 = null;
        byte[] byteArray = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byteArray = inStr.getBytes("utf-8");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().toUpperCase();
    }

    /**
     * 将字符串中的中文转成unicode
     * 
     * @param s 转unicode
     * @return 转后的字符串
     */
    public static String toUnicodeString(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
          char c = s.charAt(i);
          if (c >= 0 && c <= 255) {
            sb.append(c);
          }
          else {
           sb.append("\\u"+Integer.toHexString(c));
          }
        }
        return sb.toString();
    }

    /**
     * 判断是否为中文字符
     * 
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }
    
}

class DigestPass {
    /**
     * 
     * @param alg String 算法，通常为MD5,SHA
     * @param plainByte byte[] 明文的二进制
     * @return byte[] 二进制的消息摘要
     * @throws NoSuchAlgorithmException
     */
    public static byte[] digest(String alg, byte[] plainByte) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(alg);
        md.update(plainByte);
        return md.digest();
    }

    public static byte[] digest(String alg, byte[] plainByte, byte[] key) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(alg);
        md.update(plainByte);
        return md.digest(key);
    }
}
